package com.topcheer.gateway.filter.log;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author xutao
 * @Package com.topcheer.gateway.filter
 * @Description: 记录输入输出日志
 * @date 2020/1/4 21:48
 */
@Slf4j
public class LogGatewayFilterFactory extends AbstractGatewayFilterFactory<LogGatewayFilterFactory.Config> implements Ordered {
    public LogGatewayFilterFactory() {
        super(LogGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(LogGatewayFilterFactory.Config config) {
        return (exchage,chain) -> {
            String scheme = exchage.getRequest().getURI().getScheme();
            if (!"http".equals(scheme) && !"https".equals(scheme)) {
                return chain.filter(exchage);
            }
            RecorderServerHttpResponseDecorator response = new RecorderServerHttpResponseDecorator(exchage.getResponse());

            ServerWebExchange ex = exchage.mutate()
                    .request(new RecorderServerHttpRequestDecorator(exchage.getRequest()))
                    .response(response)
                    .build();
            return GatewayLogUtil.recorderRouteRequest(ex)
                    .then(Mono.defer(() -> chain.filter(ex)));

        };
    }

    @Override
    public int getOrder() {
        return -1;
    }

    public class Config {
    }
}
